package com.bxd.baodan.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.adapter.CommonAdapter;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.item.QAStatus;
import com.bxd.baodan.item.QesItem;
import com.bxd.baodan.item.QesItem.QuestionInfoBean.AnswerInfoBean;
import com.bxd.baodan.item.QesItem.QuestionInfoBean.AnswerInfoBean.FollowUpBean.DiscussBean;
import com.bxd.baodan.util.GlideUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.StringUtil;
import com.bxd.baodan.widget.MyListView;
import com.bxd.baodan.widget.ShareContentDialog;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

/**
 * 问问详情页
 *
 * @author syq
 */
public class QuestionDetailActivity extends BaseListActivity<AnswerInfoBean> {
    private ViewGroup headerView;
    private TextView qes_name, qes_content, qes_time, qes_ans_num;
    private ImageView qes_avatar;
    private boolean isSelf, hasBestAnswer;
    private String q_id;
    private String q_title;
    private BroadcastReceiver receiver;
    private ImageView bar_share;
    public Handler handler;

    public static final int SHARE_ERROR = 1;
    public static final int SHARE_CANCELED = 3;


    @Override
    protected int getActivityLayout() {
        return R.layout.pull_refresh_layout_no_divider;
    }

    @Override
    protected void addHeadView() {
        super.addHeadView();
        headerView = (ViewGroup) View.inflate(this, R.layout.question_detail_header_1, null);
        listView.addHeaderView(headerView);
        qes_name = (TextView) headerView.findViewById(R.id.qes_name);
        qes_content = (TextView) headerView.findViewById(R.id.qes_content);
        qes_time = (TextView) headerView.findViewById(R.id.qes_time);
        qes_ans_num = (TextView) headerView.findViewById(R.id.qes_ans_num);
        qes_avatar = (ImageView) headerView.findViewById(R.id.qes_avatar);
    }

    @Override
    protected void preDone() {
        setActionBarTitle("问题详情");
        footer = View.inflate(this, R.layout.list_no_answer, null);
        q_id = getIntent().getStringExtra("qid");
        q_title = getIntent().getStringExtra("q_title");
        if (StringUtil.isEmpty(q_title)) {
            q_title = "";
        }
        if (StringUtil.isEmpty(q_id)) {
            q_title = "";
        }
        bar_share = (ImageView) findViewById(R.id.iv_bar_right);
        bar_share.setImageResource(R.drawable.share);
        createHandler();
        //分享问题
        bar_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (loginStatus()) {
                    String title = StringUtil.isEmpty(q_title) ? "来自保险岛的分享!" : q_title;
                    ShareContentDialog scd = new ShareContentDialog(QuestionDetailActivity.this, title,
                            "来自保险岛的分享!", Constant.SHARE_QUESTION_LINK + q_id, "",
                            q_id, handler);
                    scd.show();
                }
            }
        });


        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent data) {
                // TODO: 18/2/9 判断qid,相同就刷新
              //  if (Constant.ANSWER_TO_QUESTION.equals(data.getAction())) {

                    QAStatus qaStatus = (QAStatus) data.getExtras().getSerializable("qaStatus");
                    if (!qaStatus.qid.equals(q_id)) {
                        return;
                    }
                    for (int i = 0; i < mData.size(); i++) {
                        AnswerInfoBean bean = mData.get(i);
                        if (bean.qa_id.equals(qaStatus.qaid)) {

                            bean.likenum = qaStatus.likenum;
                            bean.dislikenum = qaStatus.dislikenum;
                            bean.isLike = qaStatus.isLike;
                            bean.isDislike = qaStatus.isDislike;
                            bean.isBestAnswer = qaStatus.isBestAnswer;
                            bean.src = qaStatus.src;
                        }
                    }

                    if (qaStatus.isBestAnswer.equals("1")) {
                        hasBestAnswer = true;
                    }
                    adapter.notifyDataSetChanged();
                }
           // }
        };

        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ANSWER_TO_QUESTION);
        filter.addAction(Constant.QUESTION_TO_ANSWER);
        this.registerReceiver(receiver, filter);
        autoRefresh();
    }

    @Override
    protected String getArrayStr(String json_data) {

        final QesItem.QuestionInfoBean bean;
        try {
            bean = new Gson().fromJson(json_data, QesItem.QuestionInfoBean.class);
            Runnable runnable = new Runnable() {
                public void run() {

                    qes_name.setText(bean.u_nick);
                    qes_content.setText(bean.q_title);
                    q_title = bean.q_title;

                    qes_time.setText(bean.q_create_date);
                    qes_ans_num.setText(bean.q_answer_count);
                    GlideUtil.loadCircle(getApplicationContext(), bean.avatar, qes_avatar);
                    isSelf = false;
                    hasBestAnswer = bean.isBestAnswer.equals("1");
                    if (LoginInfo.getInstance().getUid().equals(bean.u_id)) {
                        isSelf = true;
                    }
                }
            };
            runOnUiThread(runnable);

        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }


        String list = JSONUtil.getArrayData("answer_info", json_data);


        return list;
    }


    @Override
    protected Type getTypeToken() {
        return new TypeToken<List<AnswerInfoBean>>() {
        }.getType();
    }

    @Override
    protected int getItemLayout() {
        return R.layout.qes_detail_ans_item_include;
    }

    @Override
    protected void setNetUtil() {
        netUtil = new NetUtil(this, JsonApi.QUESTION_GETANSWERS);
        netUtil.setParams("qid", q_id);
    }

    @Override
    protected void convert(final ViewHolder holder, final AnswerInfoBean item) {

        View agent_layout = holder.getView(R.id.agent_layout);
        View robot_layout = holder.getView(R.id.robot_layout);
        agent_layout.setVisibility(View.GONE);
        robot_layout.setVisibility(View.GONE);

        if (item.src.equals("6")) {
            agent_layout.setVisibility(View.GONE);
            robot_layout.setVisibility(View.VISIBLE);
            parseRobot(holder, item);
        } else {
            agent_layout.setVisibility(View.VISIBLE);
            robot_layout.setVisibility(View.GONE);
            parseAgent(holder, item);
        }

    }

    private void parseRobot(final ViewHolder holder, final AnswerInfoBean item) {

        holder.getView(R.id.robort_main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openActivity(AnswerDetailActivity.class, new String[]{"qid", "qaid"}, new String[]{q_id, item.qa_id});
            }
        });
        //回答者
        holder.setText(R.id.robot_name, item.name);
        //回答时间
        holder.setText(R.id.robot_ans_time, item.qa_create_date);
        //回答内容
        holder.setText(R.id.robot_content, item.qa_content);


        holder.setText(R.id.robot_useless, "没帮助(" + item.dislikenum + ")");
        holder.setText(R.id.robot_useful, "有帮助(" + item.likenum + ")");

        final CheckBox robot_useless = holder.getView(R.id.robot_useless);
        robot_useless.setChecked(item.isDislike.equals("1"));
        final CheckBox robot_useful = holder.getView(R.id.robot_useful);
        robot_useful.setChecked(item.isLike.equals("1"));


        robot_useful.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (robot_useful.isChecked()) {
                    if (item.isDislike.equals("1")) {
                        item.isDislike = "0";
                        item.dislikenum = Math.max(0, Integer.parseInt(item.dislikenum) - 1) + "";
                    }

                }
                showZan(item);

            }
        });

        robot_useless.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (robot_useless.isChecked()) {
                    if (item.isLike.equals("1")) {
                        item.isLike = "0";
                        item.likenum = Math.max(0, Integer.parseInt(item.likenum) - 1) + "";
                    }
                }
                showDisLike(item);
            }
        });
    }

    private void parseAgent(final ViewHolder holder, final AnswerInfoBean item) {
        //回答头像
        GlideUtil.loadCircle(getApplicationContext(), item.avatar, (ImageView) holder.getView(R.id.ans_avatar));
        //认证
        if (item.agent_mark != null && item.agent_mark.length > 0
                && Arrays.asList(item.agent_mark).contains("6")) {
            holder.getView(R.id.ans_verify).setVisibility(View.VISIBLE);
        } else {
            holder.getView(R.id.ans_verify).setVisibility(View.GONE);
        }
        if (item.agent_mark != null && item.agent_mark.length > 0
                && Arrays.asList(item.agent_mark).contains("8")) {
            holder.getView(R.id.official_iv).setVisibility(View.VISIBLE);
        } else {
            holder.getView(R.id.official_iv).setVisibility(View.GONE);
        }
        //回答者
        holder.setText(R.id.ans_name, item.name);
        //回答时间
        holder.setText(R.id.ans_time, item.qa_create_date);
        //回答内容
        holder.setText(R.id.ans_content, item.qa_content);
        //点赞数
        final TextView zan_tv = holder.getView(R.id.ans_zan_count);
        zan_tv.setText(item.likenum);
        //点赞
        ImageView zan_iv = holder.getView(R.id.ans_zan_iv);
        zan_iv.setImageResource(item.isLike.equals("0") ? R.drawable.zan_gray : R.drawable.zan_green);
        View zan_ly = holder.getView(R.id.zan_layout);
        zan_ly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showZan(item);
            }
        });


        //显示最佳答案图标 内部控制
        holder.getView(R.id.ans_best_iv).setVisibility(item.isBestAnswer.equals("1") ? View.VISIBLE : View.GONE);


        //评论按钮
        View ask = holder.getView(R.id.ans_ask);
        ask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (loginStatus()) {
                    MobclickAgent.onEvent(App.getContext(), "v6_1_3_BW_wdxq_pl");
                    openActivity(AnswerDetailActivity.class, new String[]{"qid", "qaid", "position"}, new String[]{q_id, item.qa_id, holder.getPosition() + ""});
                }
            }
        });

        //采纳按钮
        final View caina = holder.getView(R.id.ans_caina);
        if (isSelf) {

            //采纳按钮由外部控制
            caina.setVisibility(hasBestAnswer ? View.GONE : View.VISIBLE);

        } else {
            caina.setVisibility(View.GONE);

        }
        caina.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NetUtil netUtil = new NetUtil(QuestionDetailActivity.this, JsonApi.BESANSWER);
                netUtil.setParams("a_id", item.qa_id);
                netUtil.setParams("q_id", q_id);
                netUtil.postRequest("", new NetUtil.RequestStringListener() {

                    @Override
                    public void onComplete(String result) {
                        // 采纳
                        if (JSONUtil.isSuccess(result)) {
                            hasBestAnswer = true;
                            item.isBestAnswer = "1";
                            Intent intent = new Intent();
                            intent.setAction(Constant.QUESTION_TO_ANSWER);
                            QAStatus qaStatus = new QAStatus(item.isLike, item.isDislike,
                                    item.dislikenum, item.likenum,
                                    q_id, item.qa_id,
                                    item.isBestAnswer, "1",
                                    item.src);

                            intent.putExtra("qaStatus", qaStatus);

                            sendBroadcast(intent);
                            adapter.notifyDataSetChanged();
                        }
                    }
                });
            }
        });


        AnswerInfoBean.FollowUpBean followUp = item.followUp;
        List<DiscussBean> discussList = followUp.lists;
        View discuss_layout = holder.getView(R.id.ans_discuss_layout);
        if (discussList != null && discussList.size() > 0) {
            discuss_layout.setVisibility(View.VISIBLE);
            MyListView listView = holder.getView(R.id.ans_list);
            listView.setAdapter(new CommonAdapter<DiscussBean>(QuestionDetailActivity.this, discussList, R.layout.ans_item_discuss) {
                @Override
                public void convert(ViewHolder holder, DiscussBean item) {
                    TextView tv = holder.getView(R.id.content);
                    String html = "<font color='#999999'>" + item.qfu_active_user + "</font>" + "回复" + "<font color='#999999'>" + ":" + "</font>" + item.qfu_content;
                    tv.setText(Html.fromHtml(html));
                }
            });
        } else {
            discuss_layout.setVisibility(View.GONE);
        }

        holder.getView(R.id.main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openActivity(AnswerDetailActivity.class, new String[]{"qid", "qaid"}, new String[]{q_id, item.qa_id});
            }
        });
    }

    private void showZan(final AnswerInfoBean item) {
        if (loginStatus()) {

            NetUtil netUtil = new NetUtil(QuestionDetailActivity.this, JsonApi.PRAISE);
            netUtil.setParams("qaid", item.qa_id);
            netUtil.setParams("qid", q_id);
            netUtil.postRequest("", new NetUtil.RequestStringListener() {
                @Override
                public void onComplete(String result) {
                    int qaLikeStatus = 0;
                    try {
                        JSONObject json = new JSONObject(JSONUtil
                                .getData(result));
                        qaLikeStatus = json.getInt("qaLikeStatus");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (qaLikeStatus == 1) {
                        item.isLike = 1 + "";
                        item.likenum = Integer.parseInt(item.likenum + "") + 1 + "";


                    } else {
                        item.isLike = 0 + "";
                        item.likenum = Math.max(0, Integer.parseInt(item.likenum) - 1) + "";
                    }

                    Intent intent = new Intent();
                    intent.setAction(Constant.QUESTION_TO_ANSWER);
                    QAStatus qaStatus = new QAStatus(item.isLike, item.isDislike,
                            item.dislikenum, item.likenum,
                            q_id, item.qa_id,
                            item.isBestAnswer, "0",
                            item.src);

                    intent.putExtra("qaStatus", qaStatus);

                    sendBroadcast(intent);


                    adapter.notifyDataSetChanged();
                }
            });
        }
    }

    private void showDisLike(final AnswerInfoBean item) {
        if (loginStatus()) {

            NetUtil netUtil = new NetUtil(QuestionDetailActivity.this, JsonApi.ANSWERDISLIKE);
            netUtil.setParams("qaid", item.qa_id);
            netUtil.setParams("qid", q_id);
            netUtil.postRequest("", new NetUtil.RequestStringListener() {
                @Override
                public void onComplete(String result) {
                    int qaLikeStatus = 0;
                    try {
                        JSONObject json = new JSONObject(JSONUtil
                                .getData(result));
                        qaLikeStatus = json.getInt("qaLikeStatus");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (qaLikeStatus == 1) {
                        item.isDislike = 1 + "";
                        item.dislikenum = Integer.parseInt(item.dislikenum) + 1 + "";
                    } else {
                        item.isDislike = 0 + "";
                        item.dislikenum = Math.max(0, Integer.parseInt(item.dislikenum) - 1) + "";
                    }
                    Intent intent = new Intent();
                    intent.setAction(Constant.QUESTION_TO_ANSWER);
                    QAStatus qaStatus = new QAStatus(item.isLike, item.isDislike,
                            item.dislikenum, item.likenum,
                            q_id, item.qa_id,
                            item.isBestAnswer, "0",
                            item.src);

                    intent.putExtra("qaStatus", qaStatus);

                    sendBroadcast(intent);


                    adapter.notifyDataSetChanged();
                }
            });
        }
    }


    @Override
    protected void onDestroy() {

        unregisterReceiver(receiver);
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    /*
   * 监听分享的最终状态
   */
    private void createHandler() {
        if (handler == null) {

            handler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {

                    switch (msg.what) {
                        case SHARE_ERROR:
                            Toast.makeText(QuestionDetailActivity.this, "分享失败",
                                    Toast.LENGTH_SHORT).show();
                            break;

                        case SHARE_CANCELED:
                            Toast.makeText(QuestionDetailActivity.this, "取消分享",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        default:
                            break;
                    }
                    return false;
                }
            });
        }
    }
}
